<template>
  <div class="register-page">
    <NavBarNoSearch />
    <div class="register-container">
      <!-- 左侧信息区域 -->
      <div class="register-info">
        <div class="info-content">
          <h1>加入我们</h1>
          <p>创建您的账户，开启全新体验</p>
          <div class="features">
            <div class="feature-item">
              <div class="feature-icon">🎁</div>
              <div class="feature-text">新用户专享优惠福利</div>
            </div>
            <div class="feature-item">
              <div class="feature-icon">🔄</div>
              <div class="feature-text">跨设备同步您的数据</div>
            </div>
            <div class="feature-item">
              <div class="feature-icon">🛡️</div>
              <div class="feature-text">全方位保障您的账户安全</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧注册表单 -->
      <div class="register-form-container">
        <div class="register-form-wrapper">
          <h2>创建账号</h2>
          
          <div class="register-form">
            <div class="form-group">
              <label>手机号</label>
              <div class="input-with-prefix">
                <div class="prefix">+86</div>
                <input 
                  type="tel" 
                  v-model="phone" 
                  placeholder="请输入手机号" 
                  maxlength="11"
                />
              </div>
            </div>
            
            <div class="form-group">
              <label>验证码</label>
              <div class="input-with-suffix">
                <input 
                  type="text" 
                  v-model="verificationCode" 
                  placeholder="请输入验证码" 
                  maxlength="6"
                />
                <button 
                  class="verification-btn" 
                  :disabled="countdown > 0"
                  @click.prevent="sendVerificationCode"
                >
                  {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
                </button>
              </div>
            </div>
            
            <div class="form-group">
              <label>设置密码</label>
              <div class="input-with-icon">
                <input 
                  :type="showPassword ? 'text' : 'password'" 
                  v-model="password" 
                  placeholder="请设置8-20位密码" 
                  minlength="8"
                  maxlength="20"
                />
                <div class="toggle-password" @click="showPassword = !showPassword">
                  {{ showPassword ? '👁️' : '👁️‍🗨️' }}
                </div>
              </div>
              <div class="password-strength" v-if="password">
                <div class="strength-label">密码强度:</div>
                <div class="strength-meter">
                  <div 
                    class="strength-bar" 
                    :style="{ width: passwordStrength + '%', backgroundColor: passwordStrengthColor }"
                  ></div>
                </div>
                <div class="strength-text" :style="{ color: passwordStrengthColor }">
                  {{ passwordStrengthText }}
                </div>
              </div>
            </div>
            
            <div class="form-group">
              <label>确认密码</label>
              <div class="input-with-icon">
                <input 
                  :type="showConfirmPassword ? 'text' : 'password'" 
                  v-model="confirmPassword" 
                  placeholder="请再次输入密码" 
                />
                <div class="toggle-password" @click="showConfirmPassword = !showConfirmPassword">
                  {{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}
                </div>
              </div>
              <div class="password-match" v-if="password && confirmPassword">
                <span v-if="password === confirmPassword" style="color: #38a169;">
                  ✓ 密码一致
                </span>
                <span v-else style="color: #e53e3e;">
                  ✗ 密码不一致
                </span>
              </div>
            </div>
            
            <div class="agreement">
              <input type="checkbox" id="agree" v-model="agreeTerms" />
              <label for="agree">
                我已阅读并同意 <a href="#" class="terms-link">用户协议</a> 和 <a href="#" class="terms-link">隐私政策</a>
              </label>
            </div>
            
            <!-- 错误提示 -->
            <div v-if="error.show" class="error-message">
              {{ error.message }}
            </div>

            <button 
              class="register-btn" 
              @click="handleRegister"
              :disabled="!isFormValid || loading"
            >
              {{ loading ? '注册中...' : '注册' }}
            </button>
          </div>
          
          <div class="login-link">
            已有账号? <router-link to="/login">立即登录</router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { authService } from '../services/authService'
import NavBarNoSearch from './NavBarNoSearch.vue'

const router = useRouter()

// 注册表单数据
const phone = ref('')
const verificationCode = ref('')
const password = ref('')
const confirmPassword = ref('')
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const agreeTerms = ref(false)
const countdown = ref(0)

// 状态管理
const loading = ref(false)
const error = reactive({
  show: false,
  message: ''
})

// 显示错误信息
function showError(message) {
  error.show = true
  error.message = message
  
  // 3秒后自动隐藏错误信息
  setTimeout(() => {
    error.show = false
    error.message = ''
  }, 3000)
}

// 密码强度计算
const passwordStrength = computed(() => {
  if (!password.value) return 0
  
  let strength = 0
  // 长度检查
  if (password.value.length >= 8) strength += 25
  // 包含数字
  if (/\d/.test(password.value)) strength += 25
  // 包含小写字母
  if (/[a-z]/.test(password.value)) strength += 25
  // 包含大写字母或特殊字符
  if (/[A-Z]/.test(password.value) || /[^a-zA-Z0-9]/.test(password.value)) strength += 25
  
  return strength
})

// 密码强度文本
const passwordStrengthText = computed(() => {
  if (passwordStrength.value <= 25) return '弱'
  if (passwordStrength.value <= 50) return '中'
  if (passwordStrength.value <= 75) return '良好'
  return '强'
})

// 密码强度颜色
const passwordStrengthColor = computed(() => {
  if (passwordStrength.value <= 25) return '#e53e3e'
  if (passwordStrength.value <= 50) return '#ed8936'
  if (passwordStrength.value <= 75) return '#3182ce'
  return '#38a169'
})

// 表单验证
const isFormValid = computed(() => {
  return (
    phone.value.length === 11 &&
    verificationCode.value.length === 6 &&
    password.value.length >= 8 &&
    password.value === confirmPassword.value &&
    agreeTerms.value
  )
})

// 发送验证码
async function sendVerificationCode() {
  if (!phone.value || phone.value.length !== 11) {
    showError('请输入正确的手机号')
    return
  }
  
  try {
    loading.value = true
    
    // 调用authService发送验证码
    const result = await authService.sendRegisterCode(phone.value)
    
    if (result.success) {
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      showError(result.message)
    }
    
  } catch (err) {
    showError('发送验证码失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 注册处理
async function handleRegister() {
  if (!isFormValid.value) {
    if (!phone.value || phone.value.length !== 11) {
      showError('请输入正确的手机号')
      return
    }
    
    if (!verificationCode.value || verificationCode.value.length !== 6) {
      showError('请输入6位验证码')
      return
    }
    
    if (!password.value || password.value.length < 8) {
      showError('密码长度至少为8位')
      return
    }
    
    if (password.value !== confirmPassword.value) {
      showError('两次输入的密码不一致')
      return
    }
    
    if (!agreeTerms.value) {
      showError('请阅读并同意用户协议和隐私政策')
      return
    }
    
    return
  }
  
  try {
    loading.value = true
    
    // 调用authService注册
    const result = await authService.register(
      phone.value,
      password.value,
      confirmPassword.value,
      verificationCode.value
    )
    
    if (result.success) {
      // 注册成功后自动登录并跳转到首页
      router.push('/')
    } else {
      showError(result.message)
    }
    
  } catch (err) {
    showError('注册失败，请检查输入信息')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.register-page {
  min-height: 100vh;
  width: 100%;
  background-color: #f5f7fa;
  padding-top: 60px; /* 为顶部导航栏留出空间 */
}

.register-container {
  display: flex;
  min-height: calc(100vh - 60px); /* 减去导航栏高度 */
}

/* 左侧信息区域 */
.register-info {
  flex: 1;
  background: linear-gradient(135deg, #1a365d 0%, #2a4365 50%, #2c5282 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.info-content {
  max-width: 500px;
}

.info-content h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
}

.info-content p {
  font-size: 1.2rem;
  margin-bottom: 2rem;
  opacity: 0.9;
}

.features {
  margin-top: 3rem;
}

.feature-item {
  display: flex;
  align-items: center;
  margin-bottom: 1.5rem;
}

.feature-icon {
  font-size: 1.5rem;
  margin-right: 1rem;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.feature-text {
  font-size: 1.1rem;
}

/* 右侧注册表单 */
.register-form-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.register-form-wrapper {
  width: 100%;
  max-width: 450px;
  background: white;
  border-radius: 10px;
  padding: 40px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.register-form-wrapper h2 {
  font-size: 1.8rem;
  color: #2d3748;
  margin-bottom: 1.5rem;
  text-align: center;
}

/* 表单样式 */
.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #4a5568;
  font-weight: 500;
}

.input-with-prefix,
.input-with-suffix,
.input-with-icon {
  display: flex;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  overflow: hidden;
}

.prefix {
  background-color: #f7fafc;
  padding: 0 12px;
  display: flex;
  align-items: center;
  color: #4a5568;
  border-right: 1px solid #e2e8f0;
}

.input-with-prefix input,
.input-with-suffix input,
.input-with-icon input {
  flex: 1;
  padding: 12px;
  border: none;
  outline: none;
  font-size: 16px;
}

.verification-btn {
  background: none;
  border: none;
  border-left: 1px solid #e2e8f0;
  padding: 0 15px;
  color: #3182ce;
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
}

.verification-btn:disabled {
  color: #a0aec0;
  cursor: not-allowed;
}

.toggle-password {
  display: flex;
  align-items: center;
  padding: 0 12px;
  cursor: pointer;
  color: #718096;
}

/* 密码强度指示器 */
.password-strength {
  margin-top: 0.5rem;
  display: flex;
  align-items: center;
  font-size: 0.875rem;
}

.strength-label {
  margin-right: 0.5rem;
  color: #718096;
}

.strength-meter {
  flex: 1;
  height: 4px;
  background-color: #e2e8f0;
  border-radius: 2px;
  overflow: hidden;
  margin-right: 0.5rem;
}

.strength-bar {
  height: 100%;
  transition: width 0.3s, background-color 0.3s;
}

.strength-text {
  font-weight: 500;
}

/* 密码匹配指示器 */
.password-match {
  margin-top: 0.5rem;
  font-size: 0.875rem;
}

/* 协议同意 */
.agreement {
  display: flex;
  align-items: flex-start;
  margin-bottom: 1.5rem;
  font-size: 0.875rem;
  color: #4a5568;
}

.agreement input {
  margin-right: 0.5rem;
  margin-top: 0.25rem;
}

.terms-link {
  color: #3182ce;
  text-decoration: none;
}

.terms-link:hover {
  text-decoration: underline;
}

/* 错误提示 */
.error-message {
  color: #e53e3e;
  margin-bottom: 1rem;
  padding: 0.5rem;
  background-color: #fff5f5;
  border-radius: 4px;
  font-size: 0.875rem;
}

/* 注册按钮 */
.register-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #2a4365 0%, #3182ce 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.register-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #1a365d 0%, #2b6cb0 100%);
  box-shadow: 0 4px 12px rgba(49, 130, 206, 0.3);
}

.register-btn:disabled {
  background: #a0aec0;
  cursor: not-allowed;
}

/* 登录链接 */
.login-link {
  text-align: center;
  margin-top: 2rem;
  color: #718096;
}

.login-link a {
  color: #3182ce;
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-container {
    flex-direction: column;
  }
  
  .register-info {
    padding: 30px;
    min-height: 300px;
  }
  
  .register-form-container {
    padding: 20px;
  }
  
  .register-form-wrapper {
    padding: 30px;
  }
}
</style>